package com.lerays.spider.sougou.handler;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.lerays.spider.sougou.SougouSpider;
import com.lerays.spider.sougou.utils.Encryption;

/**
 * spider listener status callback listener
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class ListenerCallbackHandler implements Runnable
{
	private SougouSpider wechatSpider = null;
	private String apiUrl = null;
	private String status = null;
	
	/**
	 * construct method 
	 * 
	 * @param	apiUrl	callback api url
	 * @param	status	current spider status
	 */
	public ListenerCallbackHandler( 
			SougouSpider wechatSpider,
			String apiUrl, String status )
	{
		this.wechatSpider = wechatSpider;
		this.apiUrl	= apiUrl;
		this.status	= status;
	}

	@Override
	public void run() 
	{
		//get the current time stamp
		int timestamp = (int)(System.currentTimeMillis() / 1000);
		String key = Encryption.encrypt(timestamp+wechatSpider.getSecretKey(), "SHA1");
		
		//builder the final request url
		StringBuilder sb = new StringBuilder();
		sb.append(apiUrl)
			.append((apiUrl.indexOf('?')==-1) ? '?' : '&')
			.append("from=wechatspider")
			.append("&status=").append(status)
			.append("&timestamp=").append(timestamp)
			.append("&key=").append(key);
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(sb.toString());
		get.setHeader("User-Agent", "websnail/0.2 based leray/wechatspider/"+wechatSpider.getVersion());
		CloseableHttpResponse response = null;
		
		try {
			response = httpClient.execute(get);
			//@Note: do something with the response
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			if ( response != null ) response.close();
			httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
